<?php
namespace Framework;

use Framework\View\MyLoader;

/**
 * Twig 3.x 至少需要PHP 7.2.5才能运行。
 */
class Twig
{
    public $twig;

    public function __construct()
    {

    }


    public function loader()
    {
        // return new MyLoader();

        $loader = new \Twig\Loader\FilesystemLoader('D:\paita\templates');
        $loader->addPath('D:\paita\src\Views', 'app');

        return $loader;
    }

    public function twig()
    {
        if( $this->twig == null ){
            $options = [
                'debug' => true,
                'charset' => 'utf-8',
                'cache' => 'D:\paita\runtime\twig',//cache 字符串或false

            ];
            $this->twig = new \Twig\Environment($this->loader(), $options);
        }

        // $view->addExtension(new \Framework\View\MyExtension());
        $this->twig->getExtension(\Twig\Extension\CoreExtension::class)->setDateFormat('Y-m-d', '%d days');
        // $core = $this->twig->getExtension(\Twig\Extension\CoreExtension::class);


        // $functions = new \Twig\TwigFunction('csrf', function(){
        //     return 'csrf___';
        // });

        // $this->twig->addFunction($functions);

        // ->setTimezone('Asia/Shangha');
        // var_dump($core->getTimezone());

        // $twig->addGlobal('text', new Text());


        // $this->twig->addFilter(new \Twig\TwigFilter('csrf', function ($string) {
        //     return 'aaaaaaa';
        // }));


        return $this->twig;
    }

    //Twig 扩展是为 Twig 添加新功能的包。通过以下addExtension()方法注册扩展
    public function addExtension($extension)
    {
        return $this->twig()->addExtension($extension);
    }



    public function render($name, array $context = []): string
    {
        return $this->twig()->render($name, $context);
    }

}